from django.db.models import ForeignKey, ManyToManyField


def get_choice_text(text, field):
    """
    获取choice字段的文本
    :param text: choice字段的名称
    :param field: choice字段
    :return:
    """

    def inner(obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return text
        method = 'get_%s_display' % field
        return getattr(obj, method)()

    return inner


def get_boolean_text(text, field):
    """
    获取boolean字段的文本
    :param text: choice字段的名称
    :param field: choice字段
    :return:
    """

    def inner(obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return text
        return '是' if getattr(obj, field) else '否'

    return inner


def get_datetime_text(text, field, date_formate='%Y-%m-%d'):
    """
    获取choice字段的文本
    :param text: choice字段的名称
    :param field: choice字段
    :return:
    """

    def inner(obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return text
        datetime = getattr(obj, field)
        return datetime.strftime(date_formate)

    return inner


def get_m2m_text(text, field):
    """
    获取choice字段的文本
    :param text: choice字段的名称
    :param field: choice字段
    :return:
    """

    def inner(obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return text
        queryset = getattr(obj, field).all()
        text_list = [str(row) for row in queryset]
        return ','.join(text_list)

    return inner

def get_incomma_value(text, field):
    """
    获取choice字段的文本
    :param text: choice字段的名称
    :param field: choice字段
    :return:
    """

    def inner(obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return text
        value = getattr(obj, field)
        return "{:,}".format(value)

    return inner


class SearchGroupRow(object):
    def __init__(self, title, queryset_or_tuple, option, field_object, query_dict):
        self.queryset_or_tuple = queryset_or_tuple
        self.option = option
        self.field_object = field_object
        self.query_dict = query_dict
        self.title = title

    def __iter__(self):

        yield '<div class="whole">'
        yield self.title
        yield '</div>'
        yield '<div class="others">'
        total_query_dict = self.query_dict.copy()
        total_query_dict._mutable = True

        origin_value_list = self.query_dict.getlist(self.option.field)
        if not origin_value_list:
            yield '<a class="active" href="?%s">全部</a>' % total_query_dict.urlencode()
        else:
            total_query_dict.pop(self.option.field)
            yield '<a href="?%s">全部</a>' % total_query_dict.urlencode()
        for item in self.queryset_or_tuple:
            text = self.option.get_text(item)
            value = str(self.option.get_value(item))
            query_dict = self.query_dict.copy()
            query_dict._mutable = True
            if not self.option.is_multi:
                query_dict[self.option.field] = value
                if value in origin_value_list:
                    query_dict.pop(self.option.field)
                    yield '<a class="active" href="?%s">%s</a>' % (query_dict.urlencode(), text)
                else:
                    yield '<a href="?%s">%s</a>' % (query_dict.urlencode(), text)
            else:
                multi_value_list = self.query_dict.getlist(self.option.field)
                if value in multi_value_list:
                    multi_value_list.remove(value)
                    query_dict.setlist(self.option.field, multi_value_list)
                    yield '<a class="active" href="?%s">%s</a>' % (query_dict.urlencode(), text)
                else:
                    multi_value_list.append(value)
                    query_dict.setlist(self.option.field, multi_value_list)
                    yield '<a href="?%s">%s</a>' % (query_dict.urlencode(), text)
        yield '</div>'


class Option(object):
    def __init__(self, field, is_multi=False, db_condition=None, order_by=None, text_func=None, value_func=None):
        """
        :param field:组合搜索关联的字段
        :param db_condition: 数据库关联查询的条件
        :param is_multi: 数据库关联查询的条件
        :param text_func: 此函数用于组合搜索查询条件的文本
        :param value_func: 此函数用于组合搜索查询按钮
        """
        self.field = field
        self.is_multi = is_multi
        if not db_condition:
            db_condition = {}
        self.db_condition = db_condition
        self.text_func = text_func
        self.value_func = value_func
        self.order_by = order_by
        self.choice = False

    def get_db_condition(self):
        return self.db_condition

    def get_queryset_or_tuple(self, request, model_class, *args, **kwargs):
        # 判断获取到的model类的字段对象类型：FK或者M2M
        field_object = model_class._meta.get_field(self.field)
        title = field_object.verbose_name
        if isinstance(field_object, ForeignKey) or isinstance(field_object, ManyToManyField):
            db_condition = self.get_db_condition()
            if self.order_by:
                return SearchGroupRow(title, field_object.related_model.objects.filter(**db_condition).
                                      order_by(self.order_by), self, field_object, request.GET)
            else:
                return SearchGroupRow(title, field_object.related_model.objects.filter(**db_condition).order_by('id'),
                                      self, field_object, request.GET)
        else:
            self.choice = True
            return SearchGroupRow(title, field_object.choices, self, field_object, request.GET)

    def get_text(self, field_object):

        if self.text_func:
            return self.text_func(field_object)
        if self.choice:
            return field_object[1]
        return str(field_object)

    def get_value(self, field_object):

        if self.value_func:
            return self.value_func(field_object)
        if self.choice:
            return field_object[0]
        return field_object.pk


# 获取组合搜索查询条件
def get_search_group_condition(search_group,request):
    """
    获取组合查询条件
    :param request:
    :return:
    """
    condition = {}
    for option in search_group:
        if option.is_multi:
            value_list = request.GET.getlist(option.field)
            if not value_list:
                continue
            condition["%s__in" % option.field] = value_list
        else:
            value = request.GET.get(option.field)
            if not value:
                continue
            condition[option.field] = value
    return condition
